<template>
  <div class="manage-poi">
    <el-card class="manage-card animated">
      <h1 class="title">足迹管理</h1>
      <div class="action-bar">
        <el-button
          type="warning"
          @click="handleBatchClearNotes"
          :disabled="multipleSelection.length === 0"
          class="action-button"
        >
          清空选中记录的评价
        </el-button>
      </div>

      <el-table
        :data="footprintStore.footprints"
        v-loading="footprintStore.loading"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
        class="manage-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="user_id" label="用户ID" width="90" align="center" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="property_id" label="房产ID" width="90" align="center" />
        <el-table-column prop="property.name" label="小区名称" width="180" />
        <el-table-column prop="notes" label="用户评价" min-width="200" />
        <el-table-column prop="rating" label="用户打分" width="180" align="center">
          <template #default="scope">
            <el-rate v-model="scope.row.rating" disabled show-score text-color="#ff9900" score-template="{value} 分" />
          </template>
        </el-table-column>
        <el-table-column prop="added_at" label="收藏时间" width="170">
          <template #default="scope">
            {{ new Date(scope.row.added_at).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openEditDialog(scope.row)" class="action-button">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" class="action-button">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="footprintStore.pagination.total_items"
          :current-page="footprintStore.pagination.current_page"
          :page-size="footprintStore.pagination.per_page"
          @current-change="handlePageChange"
        />
      </div>

      <div class="bottom-right-button">
        <el-button type="danger" @click="handleExit" class="action-button">退出</el-button>
      </div>

      <el-dialog v-model="editDialogVisible" title="编辑足迹信息" width="500px" class="dialog">
        <el-form :model="editForm" label-width="100px" label-position="top">
          <el-form-item label="用户评价">
            <el-input v-model="editForm.notes" type="textarea" :rows="5" placeholder="请输入评价内容" />
          </el-form-item>
          <el-form-item label="用户打分">
            <el-rate v-model="editForm.rating" :max="5" show-score text-color="#ff9900" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useFootprintAdminStore } from '@/stores/footprintsAdmin';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const footprintStore = useFootprintAdminStore();

const multipleSelection = ref([]);
const editDialogVisible = ref(false);
const editForm = reactive({
  user_id: null,
  property_id: null,
  notes: '',
  rating: 0,
});

onMounted(() => {
  footprintStore.fetchFootprints({ page: 1 });
});

const handleExit = async () => {
  await router.push('/admin');
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handlePageChange = (page) => {
  footprintStore.fetchFootprints({ page });
};

const openEditDialog = (row) => {
  Object.assign(editForm, {
    user_id: row.user_id,
    property_id: row.property_id,
    notes: row.notes,
    rating: row.rating,
  });
  editDialogVisible.value = true;
};

const submitEdit = async () => {
  const success = await footprintStore.updateFootprint(editForm);
  if (success) {
    ElMessage.success('更新成功');
    editDialogVisible.value = false;
  }
};

const handleBatchClearNotes = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清空选中的 ${multipleSelection.value.length} 条记录的评价吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    const footprintsToClear = multipleSelection.value.map(item => ({
      user_id: item.user_id,
      property_id: item.property_id,
    }));
    await footprintStore.batchClearNotes(footprintsToClear);
    ElMessage.success('批量清空评价成功');
  } catch (error) {
    ElMessage.info('已取消批量操作');
  }
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要永久删除这条足迹记录吗 (用户: ${row.username}, 小区: ${row.property.name})？`,
      '危险操作确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await footprintStore.deleteFootprint({
      user_id: row.user_id,
      property_id: row.property_id
    });

    if (success) {
      ElMessage.success('删除成功');
    }
  } catch (error) {
    ElMessage.info('已取消删除');
  }
};
</script>

<style scoped>
@keyframes slideUpFadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.manage-poi {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); /* Consistent with App.vue */
}

.manage-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  background: #ffffff;
  animation: slideUpFadeIn 0.7s ease-out forwards;
    height: 800px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  text-align: center;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.action-button {
  border-radius: 8px;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.manage-table {
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.bottom-right-button {
  margin-top: 20px;
  text-align: right;
}

.dialog {
  border-radius: 12px;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  background-color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-textarea__inner:focus) {
  background-color: #fff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
}

@media (max-width: 768px) {
  .manage-poi {
    padding: 10px;
  }

  .manage-card {
    padding: 15px;
  }

  .title {
    font-size: 20px;
  }

  .action-button {
    padding: 8px 16px;
    font-size: 14px;
  }
}
</style>